<template>
  <div class="app-container">
    <!-- 搜索条件 -->
    <div class="filter-container">
      <el-input
        @keyup.enter.native="handleFilter"
        style="width: 200px"
        class="filter-item"
        placeholder="章节名"
        v-model="keyword"
      >
      </el-input>

      <!-- <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.type" placeholder="类型">
        <el-option v-for="item in  typeOptions" :key="item.key" :label="item.display_name+'('+item.key+')'" :value="item.key">
        </el-option>
      </el-select> -->

      <el-button
        class="filter-item"
        type="primary"
        v-waves
        icon="search"
        @click="handleFilter"
        >搜索</el-button
      >
      <el-button
        class="filter-item"
        type="primary"
        @click="handleCreate"
        icon="edit"
        >添加</el-button
      >

      <el-button
        class="filter-item"
        type="primary"
        @click="handleDelAll"
        icon="edit"
        >批量删除</el-button
      >
    </div>

    <!-- 表格 v-loading.body="listLoading"-->
    <el-table
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      :data="chapters"
      style="font-size:13px"
      border
      fit
      highlight-current-row
    >
      <el-table-column type="selection" width="50"> </el-table-column>

      <el-table-column align="center" label="序号" width="70">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

     <el-table-column label="书名" width="250" align="center">
        <template slot-scope="scope">
          {{ scope.row.novel_title }}
        </template>
      </el-table-column>

      <el-table-column label="卷名" width="250" align="center">
        <template slot-scope="scope">{{
            scope.row.roll_title
          }}
        </template>
      </el-table-column>

       <el-table-column label="章节名" width="300" align="left">
        <template slot-scope="scope">
            <el-button type="text" @click="showContent(scope.row)">{{ scope.row.chap_title | simpleIntro }}</el-button>
        </template>
      </el-table-column>

       <el-table-column label="创建时间" width="160" align="center">
        <template slot-scope="scope">
          {{ scope.row.ctime | simpleTime}}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button >
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="listQuery.currPage"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
    <!-- 内容弹框   :title="chapters[0].chapter_title"-->
    <el-dialog
        :visible.sync="ContentDialog"
        :title="content.chap_title"
        @close="ContentDialog = false"
        center
        width="60%">
        <el-input type="textarea" placeholder="请输入内容" :rows="10" v-model="content.content_text">
        </el-input>
        <span slot="footer" class="dialog-footer">
            <el-button @click="ContentDialog = false">取 消</el-button>
            <el-button type="primary" @click="submitContent">确 定</el-button>
        </span>
        </el-dialog>
    <!-- 新增弹窗 -->
    <el-dialog title="新增章节" :visible.sync="addDialog" @close="closeDialog">
      <el-form
        class="small-space"
        :model="chapter"
        label-position="left"
        label-width="70px"
        center
      >
       <el-form-item label="章节名">
          <el-input v-model="chapter.chap_title"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addDialog = false">取 消</el-button>

        <el-button type="primary" @click="handleCreateSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 弹框
      dialogVisible: false,
      ContentDialog:false,
      new_chapter_title:'',//新增章节
      chapter:{},
      chapters: [
      ],
        editDialog:false,
        addDialog:false,

      list: null, //表格list
      total: null,
      listLoading: true,
      listQuery: {
        currPage: 1,
        pageSize: 10,
      },
      roll_id:'',
      multipleSelection: [],
      keyword:'',
      is_edit:false,
      content:{}
    };
  },
   async created(){
      this.roll_id = this.$route.query.roll_id;
      console.log(this.roll_id);
      this.getList()
  },
  filters:{
    simpleTime(times){
      let date = new Date(times),
        year = date.getFullYear(),
        month = date.getMonth() +1,
        day = date.getDate(),
        h = date.getHours(),
        m = date.getMinutes()<10?'0'+date.getMinutes():date.getMinutes(),
        s = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
      return `${year}-${month}-${day} ${h}:${m}:${s}`
    },
    simpleIntro(intros){
      return intros.length>50?intros.substring(0,51)+'...':intros
    },
  },  
  methods:{
   //获取列表数据
    async getList() {
       let res = await this.$http.get('/roll_chapters',{params:{roll_id: this.roll_id, pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
      this.chapters = res.data.chapters;
      this.listQuery.currPage = parseInt(res.data.currPage)
      this.listQuery.pageSize = parseInt(res.data.pageSize)
      this.total = res.data.total
    },
     //编辑
    handleEdit(index, row) {
      this.addDialog = true;
      this.is_edit = true; //处于打开对话框状态
      this.chapter = row
      console.log("编辑的row：", index, "-----", row);
    },
   //单个删除
    handleDelete(index, row) {

        this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delFun(row)
           //前端删除。
          this.chapters.splice(index, 1);
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    delFun(row) {
      this.$http.delete('/delete_chapter',{params:{chap_id :row.chap_id}}).then(res=>{})
    },
     // 监听对话框的关闭
    closeDialog(){
      this.is_edit = false;
      this.chapter = {}
    },
    //批量删除
    handleDelAll() {
      var vm = this;
      console.log("批量删除选择的row：", vm.multipleSelection);
       this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定批量删除",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
          //前端依次执行单个删除操作
           vm.chapters = vm.chapters.filter((item)=>{
              for(let selection of vm.multipleSelection){
                if(item.chap_id === selection.chap_id){
                  return false
                }
              }
              return true;
            })
          for (var index in vm.multipleSelection) {
              console.log('======',vm.multipleSelection[index])
              vm.delFun(vm.multipleSelection[index]);
          };
          this.$message({
            type: "success",
            message: "删除成功!",
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },
    //搜索
   async handleFilter() {
      let res = await this.$http.get('/search_chapter',{params:{roll_id: this.roll_id, keyword:this.keyword, pageSize:this.listQuery.pageSize, currPage:this.listQuery.currPage}})
      this.chapters = res.data.chapters;
      this.listQuery.currPage = parseInt(res.data.currPage)
      this.listQuery.pageSize = parseInt(res.data.pageSize)
      this.total = res.data.total
      console.log(res.data);
    },
    //操作分页
    handleSizeChange(val) {
      console.log("--------一页多少条：", val);
      this.listQuery.pageSize = val;
      this.getList();
    },
    //操作分页
    handleCurrentChange(val) {
      console.log("--------当前页：", val);
      this.listQuery.currPage = val;
      this.getList();
    },
    //新增
    handleCreate() {
      this.addDialog = true;
    },
    //新增提交
     async  handleCreateSubmit() {
     let res;
     if(!this.is_edit){
         res = await  this.$http.post('/insert_chapter',{chap_title:this.chapter.chap_title, roll_id:this.roll_id})
     } else{
        res = await  this.$http.put('/update_chapter',this.chapter)
     }
     this.$message({
        type:res.data.type,
        message:res.data.message
      })
      this.getList()
      this.addDialog = false; 
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 展示内容
    async showContent(row){
      let chap_id = row.chap_id
      let res = await this.$http.get('/chap_content',{params:{chap_id}})
      this.content = res.data || {content_text:'',chap_id};
      this.$set(this.content, 'chap_title', row.chap_title)
      console.log(this.content);
      this.ContentDialog = true
    },
    //上传内容
    async submitContent(){
      let res;
      if(!this.content.content_id){
       res  = await this.$http.post('/insert_content',this.content)
      }else{
        res = await this.$http.put('/update_content',this.content)
      }
      this.$message({
        type:res.data.type,
        message:res.data.message
      })
      this.ContentDialog = false
    },
  },
};
</script>
<style>
 a:hover{
    color:rgb(237, 66, 89);
  }
</style>